package com.daisuxia.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IChannelInfoService;
import com.daisuxia.web.service.IPushUserService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.SendSmsUtil;
import com.daisuxia.web.util.encrypt.AESUtil;
import com.daisuxia.web.util.encrypt.MD5coding;

import net.sf.json.JSONObject;

@Controller
public class H5Generalize extends BaseController{
	public final static String SMS_SEND_IN_ONE_MINUTE = "SMS_SEND_IN_ONE_MINUTE_";// Redis某个手机号1分钟内已发送验证码key前缀
	public final static String SMS_REGISTER_PREFIX = "newPhoneCode_";// Redis注册key前缀
	public final static int INFECTIVE_SMS_TIME = 300;// 短信默认有效时间300秒
	private static Logger loger = Logger.getLogger(H5Generalize.class);
	
	@Autowired
	private IUserService userService;
	@Autowired
	private IPushUserService pushUserService;
	@Autowired
	private IChannelInfoService channelInfoService;
	
	/**
	 * H5 用户注册主页面
	 * 
	 */
	@RequestMapping("h5reg")
	public String h5GeneralizeHome(HttpServletRequest request, HttpServletResponse response, Model model) {
	    model.addAttribute("RCaptchaKey", "R"+request.getSession().getId());
		return "user/generalize";
	}
	/**
	 * 注册成功后显示下载APP
	 * 
	 */
	@RequestMapping("registerSuccess")
	public String registerSuccess(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "user/registerSuccess";
	}
	
	/**
	 * 获取验证码
	 */
	@RequestMapping("generalize/registerCode")
	public void registerCode(HttpServletRequest request, HttpServletResponse response, Model model) {
		String H5_REGISTER_CODE_CHECK = "h5_register_code_check";

		JSONObject json = new JSONObject();
		HashMap<String, Object> map = new HashMap<String, Object>();

		String msg = "";
		String code = "-1";
		String userPhone = "";
		
		try {
			userPhone = null == request.getParameter("phone") ? "" : request.getParameter("phone").toString();
			map.put("userPhone", userPhone);
			if (StringUtils.isBlank(userPhone)) {
				code = "-1";
				msg = "请输入手机号码";
				return;
			}
			if (!validateSubmit(request, response)) {
				code = "-1";
				msg = "图形验证码错误";
				return;
			}
		    Long remainTime=checkForFront(H5_REGISTER_CODE_CHECK, userPhone);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
         	String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度.
			User phone = new User();
			phone.setUserPhone(userPhone);
			User user = userService.searchUserByCheckTel(map);// 查询手机号码是否存在
			String content = "";
			String messageTitle = "手机短信认证";
			if (user == null) {// 注册验证码
				// 一分钟是否已经发送过验证码的key
				String hasSendOneMinKey = SMS_SEND_IN_ONE_MINUTE + userPhone;
				if (jedisCluster.get(hasSendOneMinKey) != null) {
					code = "-1";
					msg = "请一分钟后再尝试发送";
				} else {
					ServiceResult serviceResult = check(request, userPhone); 
					if (serviceResult.isFail()) {
						code = "-1";
						msg = serviceResult.getMsg();
					}else {
						jedisCluster.setex(hasSendOneMinKey, 60, userPhone);
						// 存入redis
						jedisCluster.set(SMS_REGISTER_PREFIX + userPhone, rand);
						jedisCluster.expire(SMS_REGISTER_PREFIX + userPhone, INFECTIVE_SMS_TIME);
						
						content = rand + "有效时间5分钟，您正在注册" + getAppConfig(request.getParameter("appName"), "APP_TITLE") + "账户，如不是本人请忽略。";
						
						code = "0";
						msg = "成功获取验证码";
						try {
							SendSmsUtil.sendSmsCL(userPhone, content);
							msg = "成功获取验证码";
						} catch (Exception e) {
							e.printStackTrace();
							code = "-1";
							msg = "信息发送失败稍后重试";
						}
					}
				}
			} else {
				code = "-1";
				msg = "手机号码已被注册";
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(H5_REGISTER_CODE_CHECK, userPhone);
			json.put("code", code);
			json.put("message", msg);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}
	
	/**
	 * 提交注册
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("generalize/register")
	public void registerH5(HttpServletRequest request, HttpServletResponse response) {
		String H5_REGISTER_CHECK = "h5_register_check";
		JSONObject json = new JSONObject();
		Map<String, Object> dataMap = this.getParametersO(request);
		String msg = "";
		String code = "-1";
		String userPhone = "";
		try {
			userPhone = dataMap.get("phone") + "";
			String passWord = dataMap.get("password") + "";// 获取密码
			String smsCode = dataMap.get("code") + "";// 获取手机验证码
			String channelCode = dataMap.get("channelCode") + "";// 用户注册来源渠道
			String tgFlag = request.getParameter("tgFlag");// 用户注册来源
			// 手机验证码验证
			if (StringUtils.isBlank(smsCode)) {
				msg = "手机验证码不能为空";
				return;
			}
		    Long remainTime=checkForFront(H5_REGISTER_CHECK, userPhone);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			String sendSmsCode = jedisCluster.get(SMS_REGISTER_PREFIX + userPhone);
			if ("".equals(smsCode)) {
				msg = "验证码不能为空";
				return;
			} else if (StringUtils.isBlank(sendSmsCode)) {
				msg = "验证码已失效，请重新获取 ";
				return;
			} else if (!sendSmsCode.equals(smsCode)) {
				msg = "验证码校验失败";
				return;
			}
			User invitetUser = null;
			User user = new User();
			AESUtil desEncrpt = new AESUtil();
			AESUtil aesEncrypt = new AESUtil();
			// String userPassword = desEncrpt.decrypt(passWord,"");//解密
			String Md5 = MD5coding.MD5(aesEncrypt.encrypt(passWord, ""));// 加密
			String equipmentNumber = request.getParameter("deviceId");// 设备号
			if (passWord != null) {// 密码不为空之后 做插入操作
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("userPhone", userPhone);
				User users = this.userService.searchUserByCheckTel(map);// 查询手机号码是否存在
				if (users != null) {
					code = "-1";
					msg = "手机号已经存在";
					return;
				}
				user.setUserName(userPhone);// 用户名称
				user.setPassword(Md5);// 加密后的登录密码
				user.setUserPhone(userPhone);// 用户手机号码
				user.setCreateIp(this.getIpAddr(request));// 注册时的IP地址
				user.setEquipmentNumber(userPhone);// 设备号默认为用户手机号码
				user.setAmountMax(String.valueOf(Constant.AMOUNT_MAX));
				user.setAmountAvailable(String.valueOf(Constant.AMOUNT_MAX));
				Integer channelId = null;
				if(StringUtils.isNotBlank(channelCode)) {
					channelId = channelInfoService.findChannelIdByCode(channelCode);
					if (null != channelId) {
						user.setUserFrom(channelId.toString());
					}else {
						loger.info("H5注册渠道号未找到:"+channelCode);
					}
				}else {
					loger.error("H5注册：无此渠道:"+channelCode);
				}
				if (StringUtils.isNotBlank(tgFlag)) {
					user.setTgFlag(tgFlag);
				}
				userService.saveUser(user);// 注册保存新用户
				msg = "注册成功";
				code = "0";
			} else {
				msg = "请输入6-20位密码";
			}
		} catch (Exception e) {
			code = "500";
			msg = "系统异常，请稍后再试";
			e.printStackTrace();
		} finally {
			delCheckForFront(H5_REGISTER_CHECK, userPhone);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}
}
